#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>

void* mythread(void* p){
	int sockfd = (int)(size_t)p;

    sleep(5);
    printf("close socket: %d\n", sockfd);
    close(sockfd);
    printf("close socket done: \n");

    return NULL;
}

int main(void)
{
    int sockfd;
    int len;
    struct sockaddr_in address;
    int result;
    pthread_t tid;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    address.sin_family = AF_INET;
    //注意：inet_addr函数返回的已经是按网络字节序存储的网络地址了，所以不能再加htonl了
    address.sin_addr.s_addr = inet_addr("192.168.33.92");
    address.sin_port = htons(11021);
    len = sizeof(address);

    result = connect(sockfd, (struct sockaddr*)&address, len);
    if (-1 == result)
    {
        perror("oops: client");
        exit(1);
    }
    else 
    {
        printf("connect success.\n");
    }

    pthread_create(&tid, NULL, mythread, (void*)(size_t)sockfd);
    pthread_detach(tid);

    sleep(10);
    char str[1024] = "Hello, World";
    int i = 0;
    while (1)
    {
        int writelen = write(sockfd, str, 1024);
        printf("%d write len %d\n", i++, writelen);
        usleep(10000);
    }
    
    printf("client end!!!!\n");

    return 0;
}
